package view;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import model.Level;
import model.World;

public class LevelView extends JPanel {

	private BufferedImage content;
	private Level level;
	private final World world = World.getInstance();
	
	public LevelView(){
		this.level = world.getLevel();
		//TODO: move width and height to readMapFile()
		world.WINDOW_WIDTH = level.getTiles().length*world.TILES_WIDTH;
		world.WINDOW_HEIGHT = level.getTiles()[0].length*world.TILES_HEIGHT;
		content = new BufferedImage(world.WINDOW_WIDTH, world.WINDOW_HEIGHT, BufferedImage.TYPE_INT_ARGB_PRE);
		setPreferredSize(new Dimension(world.WINDOW_WIDTH, world.WINDOW_HEIGHT));
		setOpaque(true);
		Graphics g2 = content.getGraphics();
		if(g2!=null){
			drawTiles(g2);
		}
		else
			System.out.println("null");
	}
	
	/**
	 * Draws the background and the image of the tiles.
	 */
	void drawTiles(Graphics g) {
		g.setColor(world.LEVEL_BACKGROUND_COLOR);
		g.fillRect(0, 0, level.getTiles().length*world.TILES_WIDTH, level.getTiles()[0].length*world.TILES_HEIGHT);
		for(int i=0; i<level.getTiles().length; i++){
			for(int j=0; j<level.getTiles()[0].length; j++){
				if(level.getTiles()[i][j]!=null){
					level.getTiles()[i][j].draw(g, world.TILES_WIDTH*i, world.TILES_HEIGHT*j);
				}
			}
		}
	}
	
	/**
	 * Paints all content.
	 */
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.drawImage(content, 0, 0, null);
	}

}
